package com.lihepeng.leecode.tree;

import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）。
 */
public class Solution102 {
    /**
     * 二叉树层级遍历 使用队列结构
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return res;
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> items = new ArrayList<>();
            int size = queue.size();
            for (int i = 1; i <= size; ++i) {
                TreeNode treeNode = queue.poll();
                items.add(treeNode.val);
                if (treeNode.left != null) {
                    queue.add(treeNode.left);
                }
                if (treeNode.right != null) {
                    queue.add(treeNode.right);
                }
            }
            res.add(items);
        }
        return res;
    }

    @Test
    public void runTest() {
        TreeNode head = new TreeNode(3);
        TreeNode h1 = new TreeNode(9);
        TreeNode h2 = new TreeNode(20);
        TreeNode h3 = new TreeNode(15);
        TreeNode h4 = new TreeNode(7);
        head.left = h1;
        head.right = h2;
        h2.left = h3;
        h2.right = h4;
        List<List<Integer>> lists = this.levelOrder(head);
        System.out.println(lists);
    }
}
